package com.mframe.util;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import flexjson.JSONDeserializer;
import flexjson.ObjectBinder;
import flexjson.ObjectFactory;
import flexjson.factories.BigDecimalFactory;
import flexjson.factories.BigIntegerFactory;
import flexjson.factories.BooleanObjectFactory;
import flexjson.factories.ByteObjectFactory;
import flexjson.factories.CharacterObjectFactory;
import flexjson.factories.DateObjectFactory;
import flexjson.factories.DoubleObjectFactory;
import flexjson.factories.FloatObjectFactory;
import flexjson.factories.IntegerObjectFactory;
import flexjson.factories.LongObjectFactory;
import flexjson.factories.ShortObjectFactory;

@SuppressWarnings("unchecked")
public class FlexJsonObjectBinder implements ObjectFactory {

	private Map<Class, ObjectFactory> factories;

	private FlexJsonObjectBinder() {
		factories = new HashMap<Class, ObjectFactory>();
		factories.put(Integer.class, new IntegerObjectFactory());
		factories.put(Float.class, new FloatObjectFactory());
		factories.put(Double.class, new DoubleObjectFactory());
		factories.put(Short.class, new ShortObjectFactory());
		factories.put(Long.class, new LongObjectFactory());
		factories.put(Byte.class, new ByteObjectFactory());
		factories.put(Boolean.class, new BooleanObjectFactory());
		factories.put(Character.class, new CharacterObjectFactory());
		factories.put(BigDecimal.class, new BigDecimalFactory());
		factories.put(BigInteger.class, new BigIntegerFactory());
		
		List<DateFormat> dfs = new ArrayList<DateFormat>();
		dfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
		dfs.add(new SimpleDateFormat("yyyy-MM-dd"));
		dfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		dfs.add(new SimpleDateFormat("HH:mm:ss"));
		dfs.add(new SimpleDateFormat("HH:mm"));
		factories.put(Date.class, new DateObjectFactory(dfs));
	}

	public Object instantiate(ObjectBinder context, Object value,Type targetType, Class targetClass) {
		//存在的类，并且不为“”，就按照常规来
		if(factories.get(targetClass)!=null){
			if(value!=null&&!value.toString().equals("")){
				return factories.get(targetClass).instantiate(context, value, targetType, targetClass);
			}
		}		
		return null;//否则返回null
	}

	public static <T> JSONDeserializer<T> bind(JSONDeserializer<T> jd) {
		if (jd == null)
			throw new NullPointerException("JSONDeserializer  is null");
		FlexJsonObjectBinder objFactory = new FlexJsonObjectBinder();
		for(Entry<Class, ObjectFactory> entry:objFactory.factories.entrySet()){
			jd.use(entry.getKey(), objFactory);
		}
		return jd;
	}
}